//
//  ViewController.m
//  模拟耗时操作
//
//  Created by 伍银荣 on 2021/8/20.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //线程的状态
    //新建状态
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:nil];
    //就绪状态
    [thread start];  //调用start方法线程没有立即执行,而是立即进入了就绪状态,等到cpu来调度他的时候,该线程就变成了运行状态
    //线程的threadPriority优先级属性只能说明较高优先级的线程会比较低优先级的线程具有更多的运行机会,并不是先执行完较高优先级的线程再去执行较低优先级的线程
//    for (int i = 0; i < 10; i++) {
//        //NSThread
//        //方式一:
//        //创建一个线程
//        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:nil];
//        thread.name = @"thread1";
//        thread.threadPriority = 1;
//        //开启线程(子线程)
//        [thread start];
//
//        NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:nil];
//        thread2.name = @"thread2";
//        //线程的优先级
//        thread2.threadPriority = 0;
//        [thread2 start];
//    }
    
    
    //方式二(没有返回值)
   // [NSThread detachNewThreadSelector:@selector(demo) toTarget:self withObject:nil];
    
    //方式三
    //  [self performSelectorInBackground:@selector(demo) withObject:nil];
}

- (void)demo {
    NSLog(@"hello - %@",[NSThread currentThread]);
    for(int i = 0; i < 20; i++) {
        NSLog(@"i = %d",i);
        if (i == 5) {
            //阻塞状态
            [NSThread sleepForTimeInterval:3];
        }
        if (i == 10) {
            //死亡状态(非正常死亡)
            [NSThread exit];
        }
    }
}


//void *demo(void *param) {
//    NSLog(@"hello");
//    return NULL;
//}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
 //   [self longRunning];
}

/*
 1> 循环的速度非常非常快.
 2> 操作内存的栈空间,速度非常快
 3> 操作内存的堆空间,速度有点慢
 4> 循环非常消耗CPU资源
 5> I/O(输入输出)操作,速度非常慢
 */

//模拟耗时操作
- (void)longRunning {
    for (int i = 0; i < 1000000; i++) {
        NSLog(@"--beginnig--");
       // int n = i;  //存储在栈空间
       // NSString *str = @"hello";  //存储在常量区
       // NSString *str = [NSString stringWithFormat:@"hello - %d",i];  //存储在堆区
        NSLog(@"i = %d", i);
    }
    NSLog(@"--end--");
}


@end
